//
//  LGHomeViewCell.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/17.
//

#import "LGConsultHomeViewCell.h"
#import "TUIDefine.h"
#import "TUICommonModel.h"
#import "TUITool.h"
#import "TUIThemeManager.h"
#define kScale UIScreen.mainScreen.bounds.size.width / 375.0

@interface LGConsultHomeViewCell()
/**   */
@property (nonatomic , strong)UIImageView *headView;
/**   */
@property (nonatomic , strong)UILabel *unreadLabel;
/**   */
@property (nonatomic , strong)UILabel *typeLabel;
/**   */
@property (nonatomic , strong)UILabel *nameLabel;
/**   */
@property (nonatomic , strong)UILabel *ageLabel;
/**   */
@property (nonatomic , strong)UIImageView *vipIcon;
/**  风险预警 */
@property (nonatomic , strong)UIImageView *riskView;
/**   */
@property (nonatomic , strong)UILabel *statusLabel;
/**   */
@property (nonatomic , strong)UILabel *contentLabel;
/**   */
@property (nonatomic , strong)UILabel *timeLabel;

@end

@implementation LGConsultHomeViewCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createSubView];
    }
    return  self;
}


- (void)fillWithData:(TUIConversationCellData *)converData{
    self.converData = converData;
    NSLog(@">>>???>>>%@--%@",converData.subTitle,converData.groupType);
    NSDictionary *customeDic = nil;
//    if(converData.cloudCustomData){
//        customeDic = [NSJSONSerialization JSONObjectWithData:converData.cloudCustomData options:NSJSONReadingMutableLeaves error:nil];
//    }
//    
//    if(customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0 && [customeDic.allKeys containsObject:@"customMsg"]){
//        //有自定义消息
////        NSLog(@">>customDic>>%@",customeDic);
//        
//        [self layoutSubview:[ObjectTool jsonToObject:customeDic[@"customMsg"]]];
//    }else{
//        //没有自定义消息
//        self.ageLabel.hidden = YES;
//        self.vipIcon.hidden = YES;
//        self.riskView.hidden = YES;
//        self.statusLabel.hidden = YES;
//        self.typeLabel.hidden = YES;
//        self.nameLabel.text = converData.title;
//        self.nameLabel.layer.borderWidth = 0;
//        //修改昵称
//        @weakify(self)
//        [[[RACObserve(converData, title) takeUntil:self.rac_prepareForReuseSignal]
//          distinctUntilChanged] subscribeNext:^(NSString *x) {
//            @strongify(self)
//            self.nameLabel.text = x;
//        }];
//        //修改头像
//        [self configHeadPic:converData];
//    }
//    
    
    
    
    self.contentLabel.attributedText = converData.subTitle;
    self.timeLabel.text = [TUITool convertDateToStr:converData.time];
    //未读消息
    [self configRedPoint:converData];
    
    
    
//    [self configOnlineStatusIcon:converData];
    
//    [self configDisplayLastMessageStatusImage:converData];
}

//患者信息
-(void)layoutSubview:(NSDictionary *)customeDic{
    if(customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0){
        NSDictionary *patientDic = customeDic[@"patient"];
        self.ageLabel.hidden = NO;
        self.typeLabel.hidden = NO;
        self.statusLabel.hidden = NO;
        [self.headView sd_setImageWithURL:[NSURL URLWithString:patientDic[@"avatar_url"]]];
        self.ageLabel.text = [NSString stringWithFormat:@"%@ | %@岁",patientDic[@"gender"],patientDic[@"age"]];
        //死亡标记
        if([patientDic[@"is_dead"] integerValue]>0){
            self.nameLabel.layer.borderWidth = 0.5;
            self.nameLabel.text = [NSString stringWithFormat:@" %@ ",patientDic[@"realname"]];
        }else{
            self.nameLabel.layer.borderWidth = 0;
            self.nameLabel.text = LGNSString(patientDic[@"realname"]);
        }
        //会员标识
        [self.vipIcon sd_setImageWithURL:[NSURL URLWithString:LGNSString(patientDic[@"vipicon"])]];
        if([patientDic[@"is_vip"] integerValue]>0){
            self.vipIcon.hidden = NO;
            [self.riskView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.ageLabel.mas_right).offset(viewPix(28));
            }];
        }else{
            self.vipIcon.hidden = YES;
            [self.riskView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.ageLabel.mas_right).offset(viewPix(6));
            }];
        }
        //风险预警
        if([patientDic[@"risk_level"] integerValue]>0){
            //有风险
            self.riskView.hidden = NO;
            NSString *riskPic = [NSString stringWithFormat:@"风险预警%@",patientDic[@"risk_level"]];
            self.riskView.image = [UIImage imageNamed:riskPic];
        }else{
            //无风险
            self.riskView.hidden = YES;
        }
        //咨询类型
        NSString *type = LGNSString(customeDic[@"appointment_type"]);
        if([type isEqualToString:@"2"]){
            //视频咨询
            self.typeLabel.text = @"视频";
            self.typeLabel.textColor = [UIColor colorWithString:@"#F2B65B"];
            self.typeLabel.backgroundColor = [UIColor colorWithString:@"#FFF1CF"];
            
        }else if([type isEqualToString:@"3"]){
            //专家(图文咨询)
            self.typeLabel.text = @"图文";
            self.typeLabel.textColor = [UIColor colorWithString:@"#4EA469"];
            self.typeLabel.backgroundColor = [UIColor colorWithString:@"#E5F9F2"];
            
        }else if([type isEqualToString:@"4"]){
            //团队咨询
            self.typeLabel.text = @"团队";
            self.typeLabel.textColor = [UIColor colorWithString:@"#8F7EF9"];
            self.typeLabel.backgroundColor = [UIColor colorWithString:@"#DFDAFF"];
        }else{
            self.typeLabel.hidden = YES;
        }
        
        if([LGNSString(customeDic[@"appointment_id"]) containsString:@"999999999-"]){
            self.statusLabel.textColor = [UIColor colorWithString:@"#FFFFFF"];
        }else{
            //10：待支付 20：已取消 30：待接诊 31：咨询中   40 已完成  41：已爽约  42 ：未接通  50：已退款
            NSString *state = LGNSString(customeDic[@"state"]);
            NSDictionary *statusDic = @{@"10":kThemeColor,@"20":@"#999999",@"30":kThemeColor,@"31":kThemeColor,@"40":@"#999999",@"41":@"#999999",@"42":@"#DD3030",@"50":@"#999999"};
            self.statusLabel.textColor = [UIColor colorWithString:statusDic[state]];
        }
        self.statusLabel.text = LGNSString(customeDic[@"state_name"]);
    }else{
        //没有自定义消息
        self.ageLabel.hidden = YES;
        self.vipIcon.hidden = YES;
        self.riskView.hidden = YES;
        self.statusLabel.hidden = YES;
        self.typeLabel.hidden = YES;
        self.nameLabel.text = self.converData.title;
        self.nameLabel.layer.borderWidth = 0;
        //修改昵称
        @weakify(self)
        [[[RACObserve(self.converData, title) takeUntil:self.rac_prepareForReuseSignal]
          distinctUntilChanged] subscribeNext:^(NSString *x) {
            @strongify(self)
            self.nameLabel.text = x;
        }];
        //修改头像
        [self configHeadPic:self.converData];
    }
}

//修改默认头像
-(void)configHeadPic:(TUIConversationCellData *)converData{
    if (converData.groupID.length > 0) {
        /**
         * 群组, 则将群组默认头像修改成上次使用的头像
         * If it is a group, change the group default avatar to the last used avatar
         */
        UIImage *avatar = nil;
        if (TUIConfig.defaultConfig.enableGroupGridAvatar) {
            NSString *key = [NSString stringWithFormat:@"TUIConversationLastGroupMember_%@", converData.groupID];
            NSInteger member = [NSUserDefaults.standardUserDefaults integerForKey:key];
            avatar = [TUIGroupAvatar getCacheAvatarForGroup:converData.groupID number:(UInt32)member];
        }
        converData.avatarImage = avatar ? avatar : DefaultGroupAvatarImageByGroupType(converData.groupType);;
    }
    @weakify(self)
    [[RACObserve(converData,faceUrl) takeUntil:self.rac_prepareForReuseSignal] subscribeNext:^(NSString *faceUrl) {
        @strongify(self)
        if (self.converData.groupID.length > 0) {
            /**
             * 群组头像
             * Group avatar
             */
            if (!IS_NOT_EMPTY_NSSTRING(faceUrl)) {
                /**
                 * 外部有手动设置群头像
                 * The group avatar has been manually set externally
                 */
                [self.headView sd_setImageWithURL:[NSURL URLWithString:faceUrl]
                                      placeholderImage:self.converData.avatarImage];
            } else {
                /**
                 * 外部未设置群头像，如果允许合成头像，则采用合成头像；反之则使用默认头像
                 * The group avatar has not been set externally. If the synthetic avatar is allowed, the synthetic avatar will be used; otherwise, the default avatar will be used.
                 */
                if (TUIConfig.defaultConfig.enableGroupGridAvatar) {
                    /**
                     * 允许合成头像，则采用合成头像
                     * 1. 异步根据群成员个数来获取缓存的合成头像
                     * 2. 如果有缓存，则直接使用缓存的合成头像
                     * 3. 如果没有缓存，则重新合成新头像
                     *
                     * 注意：
                     * 1. 由于「异步获取缓存」和「合成头像」耗时较长，容易引起 cell 的复用问题，故需要根据 groupID 来确认是否直接赋值。
                     * 2. 使用 SDWebImage 来实现占位，因为 SDWebImage 内部已经处理了 cell 的复用问题
                     *
                     */
                    
                    // 1. 获取缓存
                    // 1. Obtain group avatar from cache
                    
                    // fix: 由于 getCacheGroupAvatar 需要请求网络，断网时，由于并没有设置 headImageView，此时当前会话发消息，会话会上移，复用了第一条会话的头像，导致头像错乱
                    // fix: The getCacheGroupAvatar needs to request the network. When the network is disconnected, since the headImageView is not set, the current conversation sends a message, the conversation is moved up, and the avatar of the first conversation is reused, resulting in confusion of the avatar.
                    [self.headView sd_setImageWithURL:nil
                                          placeholderImage:converData.avatarImage];
                    [TUIGroupAvatar getCacheGroupAvatar:converData.groupID callback:^(UIImage *avatar, NSString *groupID) {
                        @strongify(self)
                        if ([groupID isEqualToString:self.converData.groupID]) {
                            // 1.1 callback 回调时，cell 未被复用
                            // 1.1 When the callback is invoked, the cell is not reused
                            
                            if (avatar != nil) {
                                // 2. 有缓存，直接赋值
                                // 2. Hit the cache and assign directly
                                [self.headView sd_setImageWithURL:nil
                                                      placeholderImage:avatar];
                            } else {
                                // 3. 没有缓存，异步合成新头像
                                // 3. Synthesize new avatars asynchronously without hitting cache
                                
                                [self.headView sd_setImageWithURL:nil
                                                      placeholderImage:converData.avatarImage];
                                [TUIGroupAvatar fetchGroupAvatars:converData.groupID placeholder:converData.avatarImage callback:^(BOOL success, UIImage *image, NSString *groupID) {
                                    @strongify(self)
                                    if ([groupID isEqualToString:self.converData.groupID]) {
                                        // callback 回调时，cell 未被复用
                                        // When the callback is invoked, the cell is not reused
                                        [self.headView sd_setImageWithURL:nil placeholderImage:success?image:DefaultGroupAvatarImageByGroupType(self.converData.groupType)];
                                    } else {
                                        // callback 回调时，cell 已经被复用至其他的 groupID。由于新的 groupID 合成头像时会触发新的 callback，此处忽略
                                        // When the callback is invoked, the cell has been reused to other groupIDs. Since a new callback will be triggered when the new groupID synthesizes new avatar, it is ignored here
                                    }
                                }];
                            }
                        } else {
                            // 1.2 callback 回调时，cell 已经被复用至其他的 groupID。由于新的 groupID 获取缓存时会触发新的 callback，此处忽略
                            // 1.2 When the callback is invoked, the cell has been reused to other groupIDs. Since a new callback will be triggered when the new groupID gets the cache, it is ignored here
                        }
                    }];
                } else {
                    /**
                     * 不允许使用合成头像，直接使用默认头像
                     * Synthetic avatars are not allowed, use the default avatar directly
                     */
                    [self.headView sd_setImageWithURL:nil
                                          placeholderImage:converData.avatarImage];
                }
            }
        } else {
            /**
             * 个人头像
             * Personal avatar
             */
            [self.headView sd_setImageWithURL:[NSURL URLWithString:faceUrl]
                                  placeholderImage:self.converData.avatarImage];
        }
    }];
}



//正在发送、发送失败  状态标识
- (UIImage *)getDisplayLastMessageStatusImage:(TUIConversationCellData *)convData {
    UIImage *image = nil;
    if (!convData.draftText && (V2TIM_MSG_STATUS_SENDING == convData.lastMessage.status || V2TIM_MSG_STATUS_SEND_FAIL == convData.lastMessage.status)) {
        if (V2TIM_MSG_STATUS_SENDING == convData.lastMessage.status) {
            image =  [UIImage imageNamed:TUIConversationImagePath(@"msg_sending_for_conv")];
        } else {
            image =  [UIImage imageNamed:TUIConversationImagePath(@"msg_error_for_conv")];
        }
    }
    return image;
}


- (void)configRedPoint:(TUIConversationCellData *)convData{
//    if(convData.groupID.length>0){
//
//
//    }else{
//        NSInteger count = convData.unreadCount;
//        [self displayUnreadPoint:count];
//    }
    NSInteger count = convData.unreadCount;
    [self displayUnreadPoint:count];
    
}

-(void)displayUnreadPoint:(NSInteger)count{
    self.unreadLabel.text = [NSString stringWithFormat:@"%ld",count];
    self.unreadLabel.hidden = NO;
    if(count == 0){
        self.unreadLabel.hidden = YES;
    }else if(count < 10){
        [self.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(viewPix(18)));
        }];
    }else if (count < 100){
        [self.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(viewPix(26)));
        }];
    }else if (count < 1000){
        [self.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(viewPix(36)));
        }];
    }else{
        self.unreadLabel.text = @"···";
    }
}


#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.backgroundColor = [UIColor clearColor];
    self.contentView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.headView];
    [self.headView addSubview:self.typeLabel];
    [self.contentView addSubview:self.unreadLabel];
    [self.contentView addSubview:self.nameLabel];
    [self.contentView addSubview:self.ageLabel];
    [self.contentView addSubview:self.vipIcon];
    [self.contentView addSubview:self.riskView];
    [self.contentView addSubview:self.statusLabel];
    [self.contentView addSubview:self.contentLabel];
    [self.contentView addSubview:self.timeLabel];
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(viewPix(16));
        make.width.height.equalTo(@(viewPix(46)));
        make.centerY.equalTo(self.contentView);
    }];
    [self.typeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.headView);
        make.height.equalTo(@(viewPix(15)));
    }];
    [self.unreadLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headView).offset(-viewPix(5));
        make.right.equalTo(self.headView).offset(viewPix(5));
        make.width.height.equalTo(@(viewPix(18)));
    }];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.headView.mas_right).offset(viewPix(10));
        make.top.equalTo(self.headView);
        make.height.equalTo(@(viewPix(23)));
    }];
    
    [self.ageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.nameLabel.mas_right).offset(viewPix(6));
        make.centerY.equalTo(self.nameLabel);
    }];
    [self.vipIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.ageLabel.mas_right).offset(viewPix(6));
        make.centerY.equalTo(self.nameLabel);
        make.width.height.equalTo(@(viewPix(16)));
    }];
    [self.riskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.ageLabel.mas_right).offset(viewPix(6));
        make.centerY.equalTo(self.nameLabel);
        make.width.equalTo(@(viewPix(34)));
        make.height.equalTo(@(viewPix(14)));
    }];
    
    [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-viewPix(16));
        make.centerY.equalTo(self.nameLabel);
    }];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.nameLabel);
        make.top.equalTo(self.nameLabel.mas_bottom).offset(viewPix(5));
        make.right.equalTo(self.contentView).offset(-viewPix(110));
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-viewPix(16));
        make.bottom.equalTo(self.contentLabel);
    }];
}

-(UIImageView *)headView{
    if(!_headView){
        _headView = [[UIImageView alloc]init];
        _headView.backgroundColor = [UIColor colorWithString:@"#F2F2F2"];
        _headView.contentMode = UIViewContentModeScaleAspectFit;
        _headView.cornerRidus = viewPix(23);
        _headView.clipsToBounds = YES;
    }
    return _headView;
}

-(UILabel *)typeLabel{
    if(!_typeLabel){
        _typeLabel = [UILabel lableWithText:@"" colorString:@"#288CFE" textFont:LGFontWeight(11, UIFontWeightSemibold) textAlignment:NSTextAlignmentCenter lines:1];
    }
    return _typeLabel;
}

-(UILabel *)unreadLabel{
    if(!_unreadLabel){
        _unreadLabel = [UILabel lableWithText:@"" colorString:@"#FFFFFF" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unreadLabel.backgroundColor = [UIColor colorWithString:@"#FF5218"];
        _unreadLabel.cornerRidus = viewPix(9);
        _unreadLabel.hidden = YES;
    }
    return _unreadLabel;
}

-(UILabel *)nameLabel{
    if(!_nameLabel){
        _nameLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _nameLabel.layer.borderColor = [UIColor colorWithString:@"#333333"].CGColor;
    }
    return _nameLabel;
}

-(UILabel *)ageLabel{
    if(!_ageLabel){
        _ageLabel = [UILabel lableWithText:@"" colorString:@"#999999" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _ageLabel;
}

-(UIImageView *)vipIcon{
    if(!_vipIcon){
        _vipIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
        _vipIcon.hidden = YES;
    }
    return _vipIcon;
}

-(UIImageView *)riskView{
    if(!_riskView){
        _riskView = [[UIImageView alloc]init];
        _riskView.hidden = YES;
    }
    return _riskView;
}

-(UILabel *)statusLabel{
    if(!_statusLabel){
        _statusLabel = [UILabel lableWithText:@"" colorString:kThemeColor textFont:LGFontWeight(15, UIFontWeightMedium) textAlignment:NSTextAlignmentRight lines:1];
    }
    return _statusLabel;
}

-(UILabel *)contentLabel{
    if(!_contentLabel){
        _contentLabel = [UILabel lableWithText:@"" colorString:@"#999999" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _contentLabel;
}

-(UILabel *)timeLabel{
    if(!_timeLabel){
        _timeLabel = [UILabel lableWithText:@"" colorString:@"#999999" textFont:LGFont(12) textAlignment:NSTextAlignmentRight lines:1];
    }
    return _timeLabel;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
